<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script>
    const data = [
      {
        parentId: null,
        id: 1,
        name: "张三"
      },
      {
        parentId: 1,
        id: 2,
        name: "李四"
      },
      {
        parentId: null,
        id: 3,
        name: "刘德华"
      },
      {
        parentId: 1,
        id: 4,
        name: "黎明"
      },
      {
        parentId: 4,
        id: 5,
        name: "张学友"
      }
    ]

    /*
    * 实现一个function: listToTree
    * 入参: 上面的data
    * 返回:
    *   [
          {
            "parentId": null,
            "id": 1,
            "name": "张三",
            "children": [
              {
                "parentId": 1,
                "id": 2,
                "name": "李四",
                "children": []
              },
              {
                "parentId": 1,
                "id": 4,
                "name": "黎明",
                "children": [
                  {
                    "parentId": 4,
                    "id": 5,
                    "name": "张学友",
                    "children": []
                  }
                ]
              }
            ]
          },
          {
            "parentId": null,
            "id": 3,
            "name": "刘德华",
            "children": []
          }
        ]
    * */
    function listToTree(data) {
      function findTreeNode(list, parentId) {
        const currentLevelList = list

        if (!currentLevelList.length) {return null}

        const item = currentLevelList.find(item => item.id === parentId)
        if (item) {
          return item
        } else {
          const nextLevelList = currentLevelList.reduce((prev, curr) => {
            return prev.concat(curr.children)
          }, [])
          return findTreeNode(nextLevelList, parentId)
        }
      }

      const ret = []
      data.forEach(item => {
        if (item.parentId) {
          // 找到那个对象
          const parent = findTreeNode(ret, item.parentId)
          parent.children.push({
            ...item, children: []
          })
        } else {
          ret.push({...item, children: []})
        }
      })
      return ret
    }

    console.log(listToTree(data))
  </script>
</body>
</html>
